package com.sjd.controller;

import com.sjd.pojo.Books;
import com.sjd.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询所有书籍并却返回到前端页面上
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.selectAllBooks();
        model.addAttribute("list", list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook=>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到 @RequestMapping("/allBook")请求；
    }

    //跳转到修改页面
    @RequestMapping("/toUpdate")
    public String toUpdate(int  id,Model model){
        Books books = bookService.selectBookById(id);
        model.addAttribute("qbook" ,books);
        return "updateBook";
    }

    //修改书籍请求
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("updateBook=>"+books);
        int i=bookService.modifyBook(books);
        if (i>0){
            System.out.println("添加成功"+books);
        }
        return "redirect:/book/allBook";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookId}")//Restful风格！！
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    //根据名称查询书籍
    @RequestMapping("selectBook")
    public String selectBook(String selectBookName, Model model){
        Books books = bookService.selectBook(selectBookName);

        System.out.println("books=>"+books);
        List<Books> list=new ArrayList<Books>();
        list.add(books);


        if (books==null){
            list=bookService.selectAllBooks();
            model.addAttribute("error","未查到");
        }

        model.addAttribute("list",list);
        return "allBook";
    }

}

